package com.zero2oneit.mall.search.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Description:
 *
 * @author Lee
 * @date 2021/3/17 13:16
 */
@Configuration
public class ESConfig {

    @Value("${el.hostname}")
    private String hostname;

    @Value("${el.userName}")
    private String userName;

    @Value("${el.password}")
    private String password;

    public static final RequestOptions COMMON_OPTIONS;
    static {
       RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
      /*  builder.addHeader("Authorization", "Bearer " + TOKEN);
        builder.setHttpAsyncResponseConsumerFactory(
                new HttpAsyncResponseConsumerFactory
                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));*/
        COMMON_OPTIONS = builder.build();
    }

    /**
     * 连接es
     * @return
     */
    @Bean
    public RestHighLevelClient reRestClient(){
        HttpHost host=new HttpHost(hostname, 9200, HttpHost.DEFAULT_SCHEME_NAME);
        RestClientBuilder builder=RestClient.builder(host);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient( builder);
    }

}
